package com.xm.ojbackendjudge.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xm.ojbackendcommon.common.ErrorCode;
import com.xm.ojbackendcommon.exception.BusinessException;
import com.xm.ojbackendjudge.judge.codesandbox.CodeSandbox;
import com.xm.ojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.xm.ojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;

/**
 * 远程代码沙箱
 */
public class RemoteCodeSandboxImpl implements CodeSandbox {

    public static final String AUTH_REQUEST_HEADER = "Authorization";

    public static final String AUTH_REQUEST_REQUEST = "Secret";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");

        String url = "http://localhost:8090/executeCode";
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .body(json)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_REQUEST)
                .execute()
                .body();
        if (StringUtils.isNotBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "execSandBox API Error:" + responseStr);
        }
        return JSONUtil.toBean(json, ExecuteCodeResponse.class);
    }
}
